﻿using UnityEngine;
using System.Collections;

public static class TransformExtensions
{
	public static Transform GetChildByName(this Transform parent, string name)
    {
		for(int i = 0; i < parent.childCount; i++)
		{
			if(string.Equals(name, parent.GetChild(i).name))
			{
				return parent.GetChild(i);
			}
		}
        return null;
    }

	/*
	public static Component GetComponentUpwards<T>(this Transform i_Source, T i_Component)
	{
		Transform transformToCheck = i_Source.parent;

		System.Type type = i_Component.GetType();

		while(transformToCheck.GetComponent(type) == null)
		{
			transformToCheck = transformToCheck.parent;

			if(transformToCheck == null)
			{
				return null;
			}
		}

		return transformToCheck.GetComponent(type);
	}
	*/
	
	public static Component GetComponentUpwards(this Transform i_Source, string i_Component)
	{
		Transform transformToCheck = i_Source.parent;
		
		while(transformToCheck.GetComponent(i_Component) == null)
		{
			transformToCheck = transformToCheck.parent;
			
			if(transformToCheck == null)
			{
				return null;
			}
		}
		
		return transformToCheck.GetComponent(i_Component);
	}

	public static Component GetComponentUpwards(this Transform i_Source, System.Type i_Component)
	{
		Transform transformToCheck = i_Source.parent;
		while(transformToCheck.GetComponent(i_Component) == null)
		{
			transformToCheck = transformToCheck.parent;
			
			if(transformToCheck == null)
			{
				return null;
			}
		}
		
		return transformToCheck.GetComponent(i_Component);
	}

}
